package com.yt.al.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PhoneDao extends BaseDao {

	/**
	 * 返回格式为 phone,pwd,phoneid
	 * 
	 * @return
	 */
	public String phoneAndPwd(String appName) {
		String phoneAndPwd = "";
		Connection conn = getConnect();
		ResultSet rs;
		try {
			rs = conn.createStatement().executeQuery(
					"select top 1 * from TB_Phone_Info where bRecommend=1 and blogin=0 and AppName='"
							+ appName + "' order by newid() " );
			if (rs.next()) {
				String phone = rs.getString("phone");
				String pwd = rs.getString("pwd");
				String phoneId = rs.getString("phoneid");
				phoneAndPwd = phone + "," + pwd + "," + phoneId;
				
				updateUsedState(phoneId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return phoneAndPwd;
	}
	
	public boolean updateUsedState(String phoneId) {
		boolean suc = false;
		Connection conn = getConnect();
		String sql = "";
		
		sql = "update TB_Phone_Info set blogin=4,logintime=getdate() where phoneid="
				+ phoneId;
		
		try {
			suc = conn.createStatement().execute(sql);
		} catch (Exception ex) {

		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return suc;
	}
	

	public boolean updatePhone(String phoneId, String phone, int loginState) {
		boolean suc = false;
		Connection conn = getConnect();
		String sql = "";
		if(loginState==2)
		{
			sql = "update TB_Phone_Info set blogin="+loginState+",logintime=getdate() where phone='"
					+ phone + "'";
		}
		else
		{
			sql = "update TB_Phone_Info set blogin="+loginState+",logintime=getdate() where phoneid="
					+ phoneId;
		}
		try {
			suc = conn.createStatement().execute(sql);
		} catch (Exception ex) {

		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return suc;
	}

	public List<String> getAllAppInfo() {
		List<String> appInfoList = new ArrayList<String>();
		Connection conn = getConnect();
		ResultSet rs;
		try {
			rs = conn.createStatement().executeQuery(
					"select * from TB_App_Info");
			while (rs.next()) {
				appInfoList.add(rs.getString("AppName"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return appInfoList;
	}
}
